<template  >
  <!-- 批量开票 -->
  <div class="app-container">
    <div class="search-wrapper">
      <el-collapse v-model="activeName">
        <el-collapse-item title="查询条件" name="1">
          <el-form ref="queryBatchIssueRef" :model="queryBatchIssueForm" label-width="80px" class="queryForm"
            :inline="true" size="mini">
            <!-- <el-form-item label="订单编号" prop="ggxh">
              <el-input style="width: 220px" v-model="queryBatchIssueForm.ggxh" clearable placeholder="请输入订单编号"></el-input>
            </el-form-item> -->
            <el-form-item label="开票状态" label-width="96px" prop="invoiceStatus">
              <el-select v-model="queryBatchIssueForm.invoiceStatus" clearable placeholder="全部">
                <el-option v-for="item in invoiceStatus" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="销方名称" prop="sellerName">
              <el-input style="width: 220px" v-model="queryBatchIssueForm.sellerName" clearable
                placeholder="请输入销方名称"></el-input>
            </el-form-item>
            <el-form-item label="发票种类" prop="invoiceTypes">
              <el-select v-model="queryBatchIssueForm.invoiceTypes" multiple placeholder="全部" clearable>
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="购方名称" prop="buyerName">
              <el-input style="width: 220px" v-model="queryBatchIssueForm.buyerName" clearable
                placeholder="请输入购方名称"></el-input>
            </el-form-item>
            <el-form-item label="单据号" prop="documentNr">
              <el-input style="width: 220px" v-model="queryBatchIssueForm.documentNr" clearable
                placeholder="请输入单据号"></el-input>
            </el-form-item>
            <el-form-item label="发票来源" prop="invoiceSource" label-width="90px">
            <el-select style="width: 220px" v-model="queryBatchIssueForm.invoiceSource"  placeholder="全部" clearable>
              <el-option label="全部" value=""></el-option>
              <el-option label="手工填开" value="手工填开"></el-option>
              <el-option label="批量导入" value="批量导入"></el-option>
              <el-option label="单据接口" value="单据接口"></el-option> 
            </el-select>
          </el-form-item>
            <el-form-item label="发票类型" prop="radio">
              <el-radio-group v-model="radio">
                <el-radio :label="null">全部发票</el-radio>
                <el-radio :label="1">蓝字发票</el-radio>
                <el-radio :label="2">红字发票</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item style="float: right">
              <el-button @click="reset()" size="small">重置</el-button>
              <el-button type="primary" style="margin-right: 10px" @click="searchFn()" size="small">查询</el-button>
            </el-form-item>
          </el-form>
        </el-collapse-item>
      </el-collapse>
    </div>
    <div class="btns" style="margin-bottom: 10px">
      <el-dropdown size="small" placement="bottom" trigger="click" style="margin-right: 10px" @command="exportOperate">
        <el-button class="search-btn" size="small" style="margin-top: 10px" icon="el-icon-upload" plain>
          导入信息
          <i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="excel">表格文件</el-dropdown-item>
          <el-dropdown-item command="txt">txt文件</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <!-- <el-button @click="importInfo()" size="small">导入信息</el-button> -->
      <el-button @click="deleteBatchInvoice()" size="small">批量删除</el-button>
      <el-button @click="manualBatchInvoiceFn()" size="small" :disabled="buttonDisabled">批量提交开票</el-button>
    </div>
    <div style="margin-top: 1%; height: 35px; border: 1px solid #b2d6ff; background-color: #ebf5ff">
      <span style="height: 35px; line-height: 35px; margin-left: 2%; font-size: 12.5px">
        <i class="el-icon-warning" style="color: #1890ff; font-size: small"></i>
        <span style="margin-left: 7px">
          共<span style="color: #fd6e0d" v-html="moneyFormat(total)"></span>条&nbsp;&nbsp;&nbsp; 
          不含税金额 <span style="color: #fd6e0d" v-html="moneyFormat(amount)"></span>元&nbsp;&nbsp;&nbsp; 
          税额 <span style="color: #fd6e0d" v-html="moneyFormat(tax)"></span>元&nbsp;&nbsp;&nbsp; 
          含税金额 <span style="color: #fd6e0d" v-html="moneyFormat(amountTax)"></span>元
        </span>
      </span>
    </div>
    <el-table @selection-change="selectionChange" ref="invocieTable" @row-click="handleSelect" :data="tableData"
      v-loading="loading" highlight-current-row size="small" class="tableSy" :height="heightTable">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="invoiceType" label="票种" :show-overflow-tooltip="true" width="80" header-align="center"
        align="center">
        <template slot="header">
          <inv-type-enum></inv-type-enum>
        </template>
        <template slot-scope="scope">
                    <span v-if="scope.row.invoiceType == '2'">             <el-tag
              size="mini">&nbsp;&nbsp;纸普&nbsp;&nbsp;</el-tag>           </span>          
          <span v-if="scope.row.invoiceType == '51'">             <el-tag type="success"
              size="mini">&nbsp;&nbsp;电普&nbsp;&nbsp;</el-tag>           </span>          
          <span v-if="scope.row.invoiceType == '4'">             <el-tag type="info" size="mini">通行费</el-tag>          
          </span>          
          <span v-if="scope.row.invoiceType == '0'">             <el-tag type="warning"
              size="mini">&nbsp;&nbsp;纸专&nbsp;&nbsp;</el-tag>           </span>          
          <span v-if="scope.row.invoiceType == '12'">             <el-tag type="success"
              size="mini">&emsp;机动车&emsp;</el-tag>           </span>          
          <span v-if="scope.row.invoiceType == '52'">             <el-tag size="mini">&nbsp;&nbsp;电专&nbsp;&nbsp;</el-tag>
                      </span>          
          <span v-if="scope.row.invoiceType == '61'">             <el-tag type="danger" size="mini">数电普</el-tag>          
          </span>          
          <span v-if="scope.row.invoiceType == '62'">             <el-tag type="success" size="mini">数电专</el-tag>        
              </span>        
        </template>
      </el-table-column>
      <!-- <el-table-column label="订单编号" key="productName" prop="productName" header-align="center" :show-overflow-tooltip="true" align="center" /> -->
      <el-table-column label="单据号" width="150" key="documentNr" prop="invoiceExt.documentNr" header-align="center"
        :show-overflow-tooltip="true" align="center" />

      <el-table-column label="购方名称" width="200" key="buyerName" prop="buyerName" header-align="center"
        :show-overflow-tooltip="true" align="center" />
      <el-table-column label="销方名称" width="200" key="sellerName" prop="sellerName" header-align="center" align="center"
        :show-overflow-tooltip="true" />
      <el-table-column label="发票来源" width="80" key="invoiceSource" prop="invoiceSource" header-align="center"
        align="center" :show-overflow-tooltip="true" />
      <!-- <el-table-column label="税收分类名称" key="classificationName" prop="classificationName" header-align="center" align="center" :show-overflow-tooltip="true" /> -->
      <el-table-column label="价税合计" key="invoiceTotalAmount" prop="invoiceTotalAmount" header-align="center"
        align="center" :show-overflow-tooltip="true" >
        <template slot-scope="scope">
          {{ Number(scope.row.invoiceTotalAmount).toFixed(2) }}
        </template>
      </el-table-column>

      <el-table-column label="税额" key="invoiceTax" prop="invoiceTax" header-align="center" align="center"
        :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span v-if="scope.row.invoiceTax">{{ Number(scope.row.invoiceTax).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="交付方式" key="unit" prop="unit" :show-overflow-tooltip="true" header-align="center" align="center" /> -->
      <el-table-column label="提交时间" width="150" key="invoiceExt.createDate" prop="invoiceExt.createDate"
        :show-overflow-tooltip="true" header-align="center" align="center" />
      <!-- <el-table-column label="提交人" key="includeTax" prop="includeTax" :show-overflow-tooltip="true" header-align="center" align="center" /> -->
      <el-table-column label="开票状态" prop="invoiceStatus" width="135px">
        <template slot-scope="scope">
          <div class="err-style" v-if="scope.row.invoiceStatus == '0'" style="line-height: 32px">
            <i class="el-icon-success" style="color: #67c23a; font-size: 12px; margin-top: 10px"></i>
            <div style="float: right; width: 75%">
              <el-tag size="small" type="success">未&nbsp;开&nbsp;票&nbsp;</el-tag>
            </div>
          </div>
          <div class="err-style" v-else-if="scope.row.invoiceStatus == '3'">
            <el-popover trigger="hover" placement="top">
              <el-card>
                <el-button type="text" size="small" title="点击复制" icon="el-icon-document-copy"
                  @click="handleCopyLink(scope.row.errorMsg)"></el-button>
                失败原因：{{ scope.row.errorMsg }}
              </el-card>
              <span slot="reference" class="name-wrapper">
                <i class="el-icon-warning" style=""></i>
              </span>
            </el-popover>
            <el-tag size="small" type="danger" style="margin-left: 15px">开票失败</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="备注" width="200" key="memo" prop="memo" :show-overflow-tooltip="true" header-align="center"
        align="center" />

      <el-table-column label="操作" width="175px" fixed="right" key="cz" prop="cz" :show-overflow-tooltip="true"
        header-align="center" align="center">
        <template slot-scope="scope">
          <el-button @click="Yulan(scope.row)" type="text" size="small" style="margin: 0px 9px 0px 0px">预览</el-button>

          <el-popconfirm title="确认删除?" icon="el-icon-info" placement="left" confirm-button-text="确认"
            @confirm="deleteInvoice(scope.row)" cancel-button-text="取消">
            <el-button slot="reference" type="text" size="small">删除</el-button>
          </el-popconfirm>

          <el-button @click="editInvoice(scope.row)" type="text" size="small" style="margin: 0px 9px">编辑</el-button>

          <el-button @click="manualInvoiceFn(scope.row)" type="text" size="small">开票</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页页码 -->
    <div class="footer">
      <el-pagination :small="true" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="this.pageParams.pageIndex" :page-sizes="[25, 50, 75, 100]" :page-size="this.pageParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="this.pageParams.total"></el-pagination>
    </div>
    <!-- 批量开票进度弹框 -->
    <el-dialog title="批量提交开票" :visible.sync="printListDialogVisible" :show-close="false" :close-on-click-modal="false"
      width="30%">
      <span style="font-size: 17px">批量提交发票中，本批次发票共{{ this.printListTotal }}张，当前提交第{{ this.currentPrintNum }}张。</span>
      <span slot="footer" class="dialog-footer">
        <!-- <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button> -->
      </span>
    </el-dialog>

    <el-dialog title="导入txt文件" :visible.sync="txtDialogVisible" :show-close="true" :close-on-click-modal="true"
      width="40%">
      <el-row>
        <el-col :span="16">
          <el-input type="text" readonly style="width: 71%" size="mini" id="fileName" v-model="fileName" />
        </el-col>
        <el-col :span="4">
          <!-- <el-button type="primary" size="small" @click="fileUpload" style="margin-left: 10px">浏览文件</el-button> -->
          <input size="large" type="file" style="color: white; margin-left: -80px" id="fileInput"
            @change="chooseUploadFile" accept=".txt,.TXT" />
        </el-col>
      </el-row>
      <el-row style="margin-top: 20px">
        <div id="kplxsz" style="display: none">
          开票种类：
          <el-select v-model="kplx" size="small" clearable style="width: 200px" collapse-tags>
            <el-option id="kplx" v-for="dict in options" :key="dict.label" :label="dict.label" :value="dict.value" />
          </el-select>
        </div>
        <p>
          1.标准导入模板为系统自带，请先<a href="javascript:void(0)" @click="downFile()"><i
              class="el-icon-download"></i>下载模板</a>,在下载的文件中填写内容后导入
        </p>
      </el-row>
      <el-row style="margin: 15px 0px">
        <el-col :span="5"><span style="line-height: 32px">是否匹配客户：</span> </el-col>
        <el-col :span="8">
          <el-select v-model="matchCustomer" style="width: 80%" placeholder="请选择" size="small">
            <el-option label="不匹配" value="0"></el-option>
            <el-option label="匹配编码" value="1"></el-option>
            <el-option label="匹配名称" value="2"></el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row style="margin: 15px 0px">
        <el-col :span="5"><span style="line-height: 32px">是否匹配商品：</span> </el-col>
        <el-col :span="8">
          <el-select v-model="matchProduct" style="width: 80%" placeholder="请选择" size="small">
            <el-option label="不匹配" value="0"></el-option>
            <el-option label="匹配编码" value="1"></el-option>
            <el-option label="匹配名称" value="2"></el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row style="margin: 15px 0px">
        <el-col :span="5"><span style="line-height: 32px">是否允许覆盖：</span> </el-col>
        <el-col :span="8">
          <el-select v-model="allowOverlay" style="width: 80%" placeholder="请选择" size="small">
            <el-option label="不允许覆盖" value="0"></el-option>
            <el-option label="允许覆盖" value="1"></el-option>
          </el-select>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="txtDialogVisible = false">取 消</el-button>
        <el-button type="success" size="mini" @click="importFn">导入</el-button>
      </span>
    </el-dialog>
    <!--导入错误信息提示-->
    <el-dialog title="导入失败" class="import-wrapper" :visible.sync="importFileDialog" append-to-body width="600px"
      :closeOnClickModal="false">
      <div style="margin-top: 1%; height: 35px; border: 1px solid #b2d6ff; background-color: #ebf5ff">
        <span style="height: 35px; line-height: 35px; margin-left: 2%; font-size: 12.5px">
          <i class="el-icon-warning" style="color: #1890ff; font-size: small"></i>
          <span style="margin-left: 7px">{{ this.errorMessage }}</span></span>
      </div>
      <el-table style="margin-top: 2%" ref="tableFrom" :data="errTableData"
        :header-cell-style="{ background: '#F0F2F5', color: '#909399' }" v-loading="loading" highlight-current-row
        size="small" class="tableSy" height="300px">
        <el-table-column label="行数" key="nr" prop="nr" header-align="center" :show-overflow-tooltip="true" align="center"
          width="160px" />
        <el-table-column label="失败原因" key="errorMsg" prop="errorMsg" header-align="center" align="center"
          :show-overflow-tooltip="true" />
      </el-table>
      <!-- 分页页码 -->
      <div class="footer" style="margin-top: 2%">
        <el-pagination :small="true" @size-change="errHandleSizeChange" @current-change="errHandleCurrentChange"
          :current-page="this.errPageParams.pageIndex" :page-sizes="[10, 20, 30, 50]"
          :page-size="this.errPageParams.pageSize" layout="total, sizes, prev, pager, next, jumper"
          :total="this.errPageParams.total"></el-pagination>
      </div>
      <div style="position: absolute; right: 5%; bottom: 3%">
        <el-button size="small" @click="confirmExport">导出失败原因</el-button>
      </div>
      <span slot="footer" class="dialog-footer"></span>
    </el-dialog>
    <!-- 预览发票详情 -->
    <detail-dialog ref="detailDialog"></detail-dialog>
    <Einvoice-dialog ref="einvoiceDialog"></Einvoice-dialog>
    <!-- 批量导入弹框 -->
    <import-dialog ref="importDialog"></import-dialog>
    <invoice-edit ref="invoiceEditRef"></invoice-edit>
    <authentication-dialog ref="authenticationRef"></authentication-dialog>
  </div>
</template>

<script>
import { manualInvoice } from '@/api/output/issueSearch.js'
import { copyInvoiceInfo } from '@/api/output/issue.js'
import { batchIssue, batchDelete, searchNeedIssueInvoice, sumNeedIssueInvoice, uploadTxt,searchSingleInvoice } from '@/api/output/batchIssue.js'
import { innerSearchErrorLogs, templateFileDownload } from '@/api/output/import.js'
import invTypeEnum from '@/components/inv-type/allInvType.vue'
import invoiceEdit from './dialog/invoiceEdit.vue'
import importDialog from '../commodity/import.vue'
import authenticationDialog from './dialog/authentication.vue'
import detaildialog from '../redIssue/detaildialog.vue'
import { amountToChinesse } from '@/model/out/fsInvoice.js'
import allECInvDetaildialog from '../redIssue/allECInvDetaildialog.vue'

export default {
  name: 'batchIssue',
  components: {
    'inv-type-enum': invTypeEnum,
    'invoice-edit': invoiceEdit,
    'import-dialog': importDialog,
    'authentication-dialog': authenticationDialog,
    'detail-dialog': detaildialog,
    'Einvoice-dialog': allECInvDetaildialog,
  },
  data() {
    var checkPrice = (rule, value, callback) => {
      if (!value) {
        return callback()
      } else {
        const reg = /^((0{1}\.\d{1,2})|([1-9]\d*\.{1}\d{1,2})|([1-9]+\d*)|0)$/
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入正确的单价'))
        }
      }
    }
    return {
      total: '0',
      amount: '0',
      tax: '0',
      amountTax: '0',
      heightTable: '',
      activeName: '1',
      radio: null,
      tjsx: false,
      gdsx: true,
      jjxs: false,
      goodsDrawer: false,
      buttonDisabled: false,
      matchCustomer: '0',
      matchProduct: '0',
      allowOverlay: '1',
      // 搜索框参数
      queryBatchIssueForm: {
        invoiceSource:'',
        invoiceStatus: '',
        sellerName: '',
        invoiceTypes: [],
        buyerName: '',
        positiveType: '',
        documentNr: '',
        pageSize: 25,
        pageIndex: 1,
      },
      invoiceStatus: [
        {
          value: '',
          label: '全部',
        },
        {
          value: '0',
          label: '未开票',
        },
        {
          value: '3',
          label: '开票失败',
        },
      ],
      options: [
        {
          value: '61',
          label: '数电普票',
        },
        {
          value: '62',
          label: '数电专票',
        },
        {
          value: 'DP',
          label: '数电普票(纸质)',
        },
        {
          value: 'DZ',
          label: '数电专票(纸质)',
        },
        // {
        //   value: 'zhinan',
        //   label: '收购发票(电子)',
        // },
        // {
        //   value: 'zhinan',
        //   label: '收购发票(纸质)',
        // },
        {
          value: '51',
          label: '普通发票(电子)',
        },
        {
          value: '2',
          label: '普通发票(纸质)',
        },
        {
          value: '52',
          label: '专用发票(电子)',
        },
        {
          value: '0',
          label: '专用发票(纸质)',
        },
      ],
      goodsForm: {
        productId: '',
        productName: '',
        productNr: '',
        classificationCode: '',
        classificationAbbr: '',
        classificationName: '',
        taxRate: '',
        spec: '',
        price: '',
        priceModify: '0',
        ycbz: '1',
        includeTax: '0',
        unit: '',
        taxPre: '0',
        taxPreContent: '1',
      },
      // 表格局部加载动画
      loading: false,
      // 表格数据
      tableData: [],
      pageParams: {
        pageIndex: 1,
        pageSize: 25,
        total: 0,
      },
      rules: {
        productName: [{ required: true, message: '请输入商品名称', trigger: 'change' }],
        classificationCode: [{ required: true, message: '请输入税收分类编码', trigger: 'change' }],
        includeTax: [{ required: true, message: '请选择含税标志', trigger: 'blur' }],
        price: [{ validator: checkPrice, trigger: ['blur', 'change'] }],
      },
      selection: [],
      multipleSelection: [],
      importType: '11',
      downName: '错误模板.xlsx',
      modelName: 'SAP含税模板.xlsx',
      dataUrl: '/invoiceServer/batchInvoice/uploadBatchFile',
      errorDataUrl: '/sajtProduct/productImport/errorExport',
      printListDialogVisible: false,
      printListTotal: null,
      currentPrintNum: 0,
      txtDialogVisible: false,
      fileName: '',
      TxtFile: '',
      kplx: '',
      importFileDialog: false,
      batchNr: '',
      errTableData: [],
      errPageParams: {
        pageIndex: 1,
        pageSize: 25,
        total: 0,
      },
      errorMessage: '',
      amountExcTaxSum: 0,
      taxSum: 0
    }
  },
  created() {
    this.heightTable = window.innerHeight - 410 + 'px'
    console.log('window.innerHeight', window.innerHeight)
    this.searchFn()
  },
  methods: {
    // 初始化渲染数据
    initData() {
      if (this.radio == null) {
        this.queryBatchIssueForm.positiveType = ''
      } else {
        this.queryBatchIssueForm.positiveType = this.radio
      }
      let invoiceExt = {
        documentNr: this.queryBatchIssueForm.documentNr,
      }
      var parm = {
        invoiceStatus: this.queryBatchIssueForm.invoiceStatus,
        sellerName: this.queryBatchIssueForm.sellerName,
        invoiceTypes: this.queryBatchIssueForm.invoiceTypes,
        buyerName: this.queryBatchIssueForm.buyerName,
        positiveType: this.queryBatchIssueForm.positiveType,
        pageSize: this.pageParams.pageSize,
        pageIndex: this.pageParams.pageIndex,
        invoiceExt: invoiceExt,
        invoiceSource:this.queryBatchIssueForm.invoiceSource
      }
      searchNeedIssueInvoice(parm).then((res) => {
        if (res.code == 0) {
          this.buttonDisabled = false
          this.loading = false
          this.tableData = res.data.rows
          this.pageParams.total = Number(res.data.total)
          if (this.pageParams.total === 0) {
            this.$message({ message: '查询结果为空' })
          }
          this.sumInvoice(parm)
        } else if (res.code != 0) {
          this.buttonDisabled = false
          this.$message({
            message: res.message,
            type: 'warning',
          })
          this.loading = false
        }
      })
    },

    // 查询功能
    searchFn() {
      this.loading = true
      this.pageParams.pageIndex = 1
      this.initData()
    },
    //计算发票数据
    sumInvoice(param) {
      sumNeedIssueInvoice(param)
        .then((res) => {
          if (res.code == 0) {
            let data = res.data
            this.total = data.total
            if (!(data.amount == null || data.amount == undefined || data.amount == '')) {
              this.amount = data.amount
            } else {
              this.amount = '0'
            }
            if (!(data.tax == null || data.tax == undefined || data.tax == '')) {
              this.tax = data.tax
            } else {
              this.tax = '0'
            }
            if (!(data.amountTax == null || data.amountTax == undefined || data.amountTax == '')) {
              this.amountTax = data.amountTax
            } else {
              this.amountTax = '0'
            }
          } else {
            this.$message({
              message: res.message,
              type: 'error',
            })
          }
        })
        .catch((error) => {
          this.$message({
            message: error.message,
            type: 'error',
          })
        })
    },
    // 导入信息
    exportOperate(command) {
      switch (command) {
        case 'excel':
          this.importInfo()
          break
        case 'txt':
          this.txtupload()
          break
      }
    },
    importInfo() {
      this.$refs.importDialog.fileName = ''
      this.$refs.importDialog.kplx = ''
      this.$refs.importDialog.parmShow = true
      this.$refs.importDialog.importDialogVisible = true
      this.$refs.importDialog.page = '批量开票'
    },
    txtupload() {
      this.txtDialogVisible = true
      this.fileName = ''
      this.kplx = ''
      this.TxtFile = ''
      this.fileName = ''
      let localStorageData
      localStorageData = localStorage.getItem('importArray')
      if (localStorageData) {
        let importArray = JSON.parse(localStorageData)
        this.matchCustomer = importArray.matchCustomer
        this.matchProduct = importArray.matchProduct
        this.allowOverlay = importArray.allowOverlay
        this.templateValue = importArray.templateValue
      }
      this.$nextTick(function(){
        document.querySelector('#fileInput').value = ''
      document.getElementById('kplxsz').style.display = 'none'
        })

    },
    chooseUploadFile(ev) {
      var fileList = ev.target.files
      if (fileList.length == 0) {
        return
      }
      var file = fileList[0]
      if (!file) {
        this.$message({
          message: '文件打开失败',
          type: 'warning',
        })
        this.fileName = ''
        document.querySelector('#fileInput').value = ''
        return
      } else {
        let f = file
        var readers = new FileReader()
        readers.readAsDataURL(f)
        readers.onload = function (e) { }
        this.fileName = f.name
        const reader = new FileReader()
        reader.readAsText(f, 'utf-8') // input.files[0]为第一个文件
        reader.onload = () => {
          const txtString = reader.result
          const patrn = /[\u4E00-\u9FA5]|[\uFE30-\uFFA0]/gi
          const luanma = '�'
          // 检测当前文本是否含有中文（如果没有，则当乱码处理）
          // 两个格式的英文编码一样，所以纯英文文件也当成乱码再处理一次
          if (!patrn.exec(txtString) || txtString.search(luanma) != -1) {
            const reader_gb2312 = new FileReader()
            // 再拿一次纯文本，这一次拿到的文本一定不会乱码
            reader_gb2312.readAsText(f, 'gb2312')
            reader_gb2312.onload = () => {
              //读取数据预处理
              const gbString = reader_gb2312.result
              var tx = gbString.split('\r\n')
              var bt = tx[0]
              var btArray = bt.split('~~')
              var bz = btArray[0]
              if (bz !== 'SJJK0101') {
                this.$message({
                  showClose: true,
                  message: '表单标示有误',
                  type: 'message',
                })
                return
              } else {
                this.setfplx(tx)
                this.TxtFile = tx
                return
              }
            }
          } else {
            var tx = txtString.split('\r\n')
            var bt = tx[0]
            var btArray = bt.split('~~')
            var bz = btArray[0]
            if (bz !== 'SJJK0101') {
              this.$message({
                showClose: true,
                message: '表单标示有误',
                type: 'message',
              })
              return
            } else {
              this.setfplx(tx)
              this.TxtFile = tx
              return
            }
          }
        }
      }
    },
    setfplx(tx) {
      for (var i = 0; i < tx.length; i++) {
        if (tx[i] !== '') {
          let da=tx[i]
          let len = da.split('~~')
          if(len.length>10){//新旧主体都大于10列 同时剔除空白行以及“//”行
            let nullType=false
            if(len.length==13){//旧文本无发票类型
              nullType=true
            }else if(len.length==14||len.length==16){//14 旧文本有发票类型无交付邮箱手机 16旧文本有发票类型交付邮箱手机
              if (len[13] === '') {//有邮箱类型但值为空
                nullType=true
              }
            }else if(len.length==18){//新文本无发票类型 18 新文本无交付邮箱手机  16 旧文本有交付邮箱手机
              nullType=true
            }
            if(nullType==true){
              this.$message({
                showClose: true,
                message: '请手动选择开票种类',
                type: 'message',
              })
              document.getElementById('kplxsz').style.display = 'block'
              this.kplx = ''
            }
            break
          }
          // if ('//' === tx[i].substring(0, 2)) {
          //   let da = tx[i + 1]
          //   let len = da.split('~~')
          //   if (len.length < 14) {
          //     this.$message({
          //       showClose: true,
          //       message: '请手动选择开票种类',
          //       type: 'message',
          //     })
          //     document.getElementById('kplxsz').style.display = 'block'
          //     this.kplx = ''
          //     break
          //   } else if (len[13] === '') {
          //     this.$message({
          //       showClose: true,
          //       message: '请手动选择开票种类',
          //       type: 'message',
          //     })
          //     document.getElementById('kplxsz').style.display = 'block'
          //     this.kplx = ''
          //     break
          //   }
          // }
        }
        document.getElementById('kplxsz').style.display = 'none'
        this.kplx = ''
      }
    },
    importFn() {
      var style = document.getElementById('kplxsz').style.display
      if (style == 'block' && this.kplx == '') {
        this.$message({
          showClose: true,
          message: '请先选择开票种类',
          type: 'message',
        })
        return
      }
      if (this.TxtFile == null || this.TxtFile == '') {
        this.$message({
          showClose: true,
          message: '请先选择上传文件',
          type: 'message',
        })
        return
      }
      let param = {
        invoiceType: '',
        tableValue: '',
      }
      var data = ''
      for (var i = 0; i < this.TxtFile.length; i++) {
        var dt = this.TxtFile[i]
        if (dt != '') {
          dt = dt.replace(/\r\n/g, '//r//n').replace(/\n/g, '//r//n')
          var k = i + 1
          data += dt + '~~' + k + '\r\n'
        }
      }

      param.tableValue = data
      param.matchCustomer = this.matchCustomer
      param.matchProduct = this.matchProduct
      param.allowOverlay = this.allowOverlay
      if (style == 'block') {
        param.invoiceType = this.kplx
      }
      const loading = this.$loading({
        lock: true,
        text: '导入数据中请稍等...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      uploadTxt(param).then((res) => {
        if (res.code == 0) {
          loading.close()
          if (res.data.rows != undefined && res.data.rows.length != 0) {
            this.batchNr = res.data.rows[0].batchNr
            this.errorMessage = res.message
            this.errTableData = res.data.rows
            this.errPageParams.total = Number(res.data.total)
            this.importFileDialog = true
          } else {
            this.$message({
              message: res.message,
              type: 'success',
            })
            this.searchFn()
          }
          this.txtDialogVisible = false
          this.importLocalStorage()
        } else {
          this.$message({
            message: res.message,
            type: 'error',
          })
          loading.close()
        }
        // this.fileName = ''
        // document.querySelector('#fileInput').value = ''
      })
    },
    importLocalStorage() {
      let paramsData = {
        templateValue: this.templateValue,
        matchCustomer: this.matchCustomer,
        matchProduct: this.matchProduct,
        allowOverlay: this.allowOverlay,
      }
      localStorage.setItem('importArray', JSON.stringify(paramsData))
    },
    // 单张删除
    deleteInvoice(val) {
      let selection = []
      selection = this.selection
      if (val !== '' || val !== undefined) {
        selection = []
        selection[0] = val.invoiceId
      }
      batchDelete(selection).then((res) => {
        if (res.code == 0) {
          this.$message({
            showClose: true,
            message: '删除成功！',
            type: 'success',
          })
          this.searchFn()
        } else if (res.code != 0) {
          this.$message({
            message: res.message,
            type: 'warning',
          })
          this.loading = false
        }
      })
    },
    //批量删除
    deleteBatchInvoice() {
      var seldata = this.$refs.invocieTable.selection
      if (seldata == null || seldata == '') {
        this.$message({
          showClose: true,
          message: '请至少选择一条数据！',
          type: 'warning',
        })
        return
      }
      let ids = []
      for (let i = 0; i < seldata.length; i++) {
        ids.push(seldata[i].invoiceId)
      }
      this.$confirm('确认删除这选中的' + seldata.length + '条信息吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        batchDelete(ids).then((res) => {
          if (res.code == 0) {
            this.$message({
              showClose: true,
              message: '删除成功！',
              type: 'success',
            })
            this.searchFn()
          } else {
            this.$Message.Error('删除失败！原因:' + res.message)
          }
        })
      })
    },
    async manualBatchInvoiceFn() {
      var seldata = this.$refs.invocieTable.selection
      if (seldata == null || seldata == '') {
        this.$message({
          showClose: true,
          message: '请至少选择一条数据！',
          type: 'warning',
        })
        return
      }
      let ids = []
      for (let i = 0; i < seldata.length; i++) {
        ids.push(seldata[i].invoiceId)
      }
      // const loading = this.$loading({
      //   lock: true,
      //   text: 'Loading',
      //   spinner: 'el-icon-loading',
      //   background: 'rgba(0, 0, 0, 0.7)',
      // })
      this.printListTotal = ids.length
      this.printListDialogVisible = true
      for (let i = 0; i < ids.length; i++) {
        this.currentPrintNum = i + 1
        let selection = []
        selection[0] = ids[i]
        const res = await batchIssue(selection)
        if (res.code == 0) {
          if (i || i == 0) {          
            if (this.currentPrintNum >= ids.length) {
              setTimeout(() => {
              this.printListDialogVisible = false               
              }, 500);
              this.$message({
                showClose: true,
                message: '批量开票调用结束',
                type: 'primary',
              })
              this.searchFn()
            }
          }
          // this.invoiceListPrint = false
        } else {
          this.$message({
            message: res.message,
            type: 'error',
          })
          this.printListDialogVisible = false
          if (res.message == '扫脸认证已超时，请重新认证') {
            setTimeout(() => {
              this.$refs.authenticationRef.authenticationVisible = true
              this.$refs.authenticationRef.buildQRCodeMethod()           
            }, 300)
            return;
          }
        }
      }
      // batchIssue(ids).then((res) => {
      //   if (res.code == 0) {
      //     this.buttonDisabled = true
      //     this.$message({
      //       showClose: true,
      //       message: res.data,
      //       type: 'primary',
      //     })
      //     loading.close()
      //     this.searchFn()
      //   } else if (res.code != 0) {
      //     this.$message({
      //       message: res.message,
      //       type: 'warning',
      //     })
      //     loading.close()
      //     this.loading = false
      //     this.buttonDisabled = false
      //   }
      // })
    },
    // 单张开票
    manualInvoiceFn(val) {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      let selection = []
      selection[0] = val.invoiceId
      batchIssue(selection).then((res) => {
        if (res.code == 0) {
          this.$message({
            showClose: true,
            message: res.data,
            type: 'primary',
          })
          loading.close()
          this.searchFn()
        } else if (res.code != 0) {
          this.$message({
            message: res.message,
            type: 'error',
          })
          loading.close()

          if (res.message == '扫脸认证已超时，请重新认证') {
            setTimeout(() => {
              this.$refs.authenticationRef.authenticationVisible = true
              this.$refs.authenticationRef.buildQRCodeMethod()           
            }, 300)
          }
        }
      })
    },
    // 编辑发票
    editInvoice(row) {
      let param = {
        invoiceId: row.invoiceId,
      }
      copyInvoiceInfo(param).then((res) => {
        if (res.code == 0) {
          this.$refs.invoiceEditRef.initData(res.data, res.data.items, row.invoiceId)
          this.$refs.invoiceEditRef.invoiceDrawervisible = true
        } else if (res.code != 0) {
          this.$message({
            message: res.message,
            type: 'error',
          })
        }
      })
    },
    //预览
    Yulan(row) {
      let param = {
        invoiceId: row.invoiceId,
      }
      const loading = this.$loading({
        lock: true,
        text: '查询数据中请稍等...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      if (row.invoiceType == '61' || row.invoiceType == '62'){
        copyInvoiceInfo(param).then((res) => {
          loading.close()
          this.$refs.einvoiceDialog.naturalPerson = res.data.naturalPerson
          this.$refs.einvoiceDialog.invoiceForm = res.data
          if(this.$refs.einvoiceDialog.invoiceForm.checker){
            this.$refs.einvoiceDialog.invoiceForm.checker= res.data.checker.replace (/\s*/g,"") 
          }
          if(this.$refs.einvoiceDialog.invoiceForm.payee){
            this.$refs.einvoiceDialog.invoiceForm.payee= res.data.payee.replace (/\s*/g,"")   
          }     
          this.$refs.einvoiceDialog.hzItemTable = res.data.items
          if (res.data.invoiceType == "61") {
            this.$refs.einvoiceDialog.invoiceTitle = "电子发票（普通发票）"
          } else {
            this.$refs.einvoiceDialog.invoiceTitle = "电子发票（增值税专用发票）"
          }
          if (res.code == 0) {
            if (res.data.items != undefined) {
              this.$refs.einvoiceDialog.detailDialogVisible = true
            } else {
              this.$message({
                message: '预览票据失败,返回参数为空！',
                type: 'error',
              })
            }
          }
          if (res.code != 0) {
            this.$message({
              message: res.message,
              type: 'error',
            })
          }
        })
      }else{

     
      copyInvoiceInfo(param).then((res) => {
        if (res.code == 0) {
          loading.close()
          this.$refs.detailDialog.invoiceForm.invcode = res.data.invoiceCode
          this.$refs.detailDialog.invoiceForm.invnr = res.data.invoiceNr
          this.$refs.detailDialog.invoiceForm.invdate = res.data.invoiceDate
          this.$refs.detailDialog.invoiceForm.custname = res.data.buyerName
          this.$refs.detailDialog.invoiceForm.custtaxnr = res.data.buyerTaxNr
          this.$refs.detailDialog.invoiceForm.custaddrtel = res.data.buyerAddress + res.data.buyerTel
          this.$refs.detailDialog.invoiceForm.custbankacct = res.data.buyerBankName + res.data.buyerBankAccount
          this.$refs.detailDialog.invoiceForm.sellername = res.data.sellerName
          this.$refs.detailDialog.invoiceForm.sellertaxnr = res.data.sellerTaxNr
          this.$refs.detailDialog.invoiceForm.selleraddresstel = res.data.sellerAddress + res.data.sellerTel
          this.$refs.detailDialog.invoiceForm.sellerbankacct = res.data.sellerBankName + res.data.sellerBankAccount
          this.$refs.detailDialog.invoiceForm.issuer = res.data.issuer
          this.$refs.detailDialog.invoiceForm.checker = res.data.checker
          this.$refs.detailDialog.invoiceForm.payee = res.data.payee
          this.$refs.detailDialog.invoiceForm.memo = res.data.memo
          this.$refs.detailDialog.invoiceForm.listMark = res.data.listMark
          this.$refs.detailDialog.invoiceForm.positiveType = res.data.positiveType
          this.$refs.detailDialog.invoiceForm.detailsList = res.data.items
          if(res.data.invoiceTdysExts.length!=0){
            this.$refs.detailDialog.invoiceForm.tdysCode = res.data.invoiceTdysExts[0].tdysCode
          }
          if (res.data.items.length > 8 && (res.data.invoiceType == '2' || res.data.invoiceType == '0')) {
            this.$refs.detailDialog.invoiceForm.listMark = '1'
            let dataList = res.data.items
            this.amountExcTaxSum = 0
            this.taxSum = 0
            for (let i = 0; i < dataList.length; i++) {
              this.amountExcTaxSum += Number(dataList[i].amountExcTax)
              this.taxSum += Number(dataList[i].tax)
            }
            this.$refs.detailDialog.amountExcTaxSum = this.amountExcTaxSum.toFixed(2)
            this.$refs.detailDialog.taxSum = this.taxSum.toFixed(2)
            let totalamountDX = Number(this.amountExcTaxSum.toFixed(2)) + Number(this.taxSum.toFixed(2))
            this.$refs.detailDialog.totalamount = (totalamountDX).toFixed(2)
            this.$refs.detailDialog.totalamountDX = amountToChinesse(totalamountDX)
          } else {
            this.$refs.detailDialog.invoiceForm.listMark = '0'
          }
          if (res.data.invoiceType == '2') {
            this.$refs.detailDialog.invoiceTitle = '增值税普通发票'
          }
          if (res.data.invoiceType == '0') {
            this.$refs.detailDialog.invoiceTitle = '增值税专用发票'
          }
          if (res.data.invoiceType == '51') {
            this.$refs.detailDialog.invoiceTitle = '增值税电子普通发票'
          }
          if (res.data.invoiceType == '52') {
            this.$refs.detailDialog.invoiceTitle = '增值税电子专用发票'
          }
          // if (res.data.invoiceType == '61') {
          //   this.$refs.detailDialog.invoiceTitle = '增值税数电普通发票'
          // }
          // if (res.data.invoiceType == '62') {
          //   this.$refs.detailDialog.invoiceTitle = '增值税数电专用发票'
          // }
          if (res.data.invoiceType == '12') {
            this.$refs.detailDialog.invoiceTitle = '机动车销售发票'
          }

          if (res.code == 0 && res.data.invoiceCode != undefined) {
            this.$refs.detailDialog.kpShow = false
            this.$refs.detailDialog.detailDialogVisible = true
          } else {
            this.$message({
              message: '该发票暂不支持预览！',
              type: 'warning',
            })
            return
          }
        } else if (res.code != 0) {
          this.$message({
            message: res.message,
            type: 'error',
          })
        }
      }) 
    }
    },

    // 选中修改时
    selectionChange(val) {
      this.selection = []
      val.forEach((element) => {
        this.selection.push(element.invoiceId)
      })
    },
    //点击某行选中该行
    handleSelect(row, event, column) {
      this.$refs.invocieTable.toggleRowSelection(row)
    },

    //重置表单
    reset() {
      this.$refs['queryBatchIssueRef'].resetFields()
      this.radio = null
    },
    //分页
    handleSizeChange(val) {
      this.pageParams.pageSize = val
      this.initData()
    },
    handleCurrentChange(val) {
      this.pageParams.pageIndex = val
      this.initData()
    },

    //错误信息
    errHandleSizeChange(val) {
      this.errPageParams.pageSize = val
      this.pageChage()
    },
    errHandleCurrentChange(val) {
      this.errPageParams.pageIndex = val
      this.pageChage()
    },
    pageChage() {
      let param = {
        batchNr: this.batchNr,
        pageIndex: null,
        pageSize: null,
      }
      param.pageIndex = this.errPageParams.pageIndex
      param.pageSize = this.errPageParams.pageSize
      innerSearchErrorLogs(param).then((res) => {
        if (res.code == 0) {
          if (res.data.rows != undefined) {
            this.errTableData = res.data.rows
            this.errPageParams.total = Number(res.data.total)
            this.importFileDialog = true
          } else {
            this.$message({
              message: res.message,
              type: 'success',
            })
          }
        } else {
          this.$message({
            message: res.message,
            type: 'error',
          })
        }
        this.fileName = ''
        document.querySelector('#fileInput').value = ''
      })
    },
    confirmExport() {
      let fd = new FormData()
      fd.append('lsh', this.batchNr)
      uploadData(fd, this.errorDataUrl).then((res) => {
        if (res.code == 0) {
          let fileName = new Date().getTime() + this.downName
          let base64data = res.data
          let blob = this.dataURLtofileBlob(base64data)
          if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            window.navigator.msSaveOrOpenBlob(blob, fileName)
            this.dialogVisible = false
          } else {
            /* 火狐谷歌的文件下载方式 */
            const url = window.URL.createObjectURL(blob)
            const link = document.createElement('a') // 创建a标签
            link.href = url
            link.download = fileName // 文件重命名，若无需重命名，将该行删去
            link.click()
            URL.revokeObjectURL(url) // 释放内存
            this.dialogVisible = false
          }
        }
      })
      // this.dialogVisible=false;
    },
    // 复制错误信息
    handleCopyLink(val) {
      let _this = this
      this.$copyText(val).then(
        function (e) {
          _this.$message({
            showClose: true,
            message: '复制成功',
            type: 'success',
          })
        },
        function (e) {
          _this.$message({
            showClose: true,
            message: '复制失败，请手动复制',
            type: 'error',
          })
        }
      )
    },
    downFile() {
      let fd = new FormData()
      fd.append('type', '1')
      fd.append('id', '')
      let fileName = 'txt.zip'
      templateFileDownload(fd)
        .then((res) => {
          if (res.code == 0) {
            let base64data = res.data
            let blob = this.dataURLtofileBlob(base64data)
            if (window.navigator && window.navigator.msSaveOrOpenBlob) {
              window.navigator.msSaveOrOpenBlob(blob, fileName)
            } else {
              /* 火狐谷歌的文件下载方式 */
              const url = window.URL.createObjectURL(blob)
              const link = document.createElement('a') // 创建a标签
              link.href = url
              link.download = fileName // 文件重命名，若无需重命名，将该行删去
              link.click()
              URL.revokeObjectURL(url) // 释放内存
            }
          } else {
            this.$message.error(res.message)
          }
        })
        .catch((error) => {
          this.$message.error(error.data)
        })
    },
    dataURLtofileBlob(dataURI) {
      var byteString = window.atob(dataURI) //base64 解码
      var arrayBuffer = new ArrayBuffer(byteString.length) //创建缓冲数组
      var intArray = new Uint8Array(arrayBuffer) //创建视图
      for (var i = 0; i < byteString.length; i++) {
        intArray[i] = byteString.charCodeAt(i)
      }
      return new Blob([intArray], { type: 'multipart/form-data' })
    },
    //金额增加千分位
    moneyFormat(value) {
      return value.replace(/(\d{1,3})(?=(\d{3})+(?:$|\.))/g, '$1,');
    }
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped >
.search-wrapper {
  text-align: left;
  box-shadow: 2px 2px 4px 2px rgba(0, 0, 0, 0.12), 0 0 6px 0 rgba(0, 0, 0, 0.04);
  margin-bottom: 25px;
}

.search-wrapper ::v-deep .el-collapse-item__content {
  padding-bottom: 0px !important;
}

.search-wrapper ::v-deep .el-collapse-item__header {
  padding-left: 15px !important;
}

.footer {
  position: sticky;
  bottom: -10px;
  width: 100%;
  height: 30px;
  line-height: var(--footer-height);
  background: #f5f7f9;
  z-index: 100;
}

.costFormItem {
  width: 90%;
  float: right;
}

.costFormInput {
  width: 100%;
}

::v-deep .divClass {
  width: 45%;
  display: inline-block;
  float: right;
  margin-right: 7%;
}

.queryForm /deep/.el-form-item__label {
  width: 90px !important;
}

.queryForm /deep/.el-select {
  width: 220px !important;
}

.queryForm /deep/.el-cascader .el-input {
  width: 220px !important;
}

.el-icon-warning {
  color: #f56c6c;
}

.import-wrapper /deep/ .el-dialog__body {
  padding: 0px 20px 30px 20px !important;
}

.import-wrapper /deep/ .el-divider--horizontal {
  margin: 5px 0px 15px 0px !important;
}</style>
